function getTarget(event) {
    var trg;
    if($.browser.msie) {
        trg = event.srcElement;
    } else {
        trg = event.target;
    }
    return trg;
}

function expandTextArea(event) {
    var trg = event.target || event.secElement;
    //getTarget(event);

    var strCount = $(trg).val().split("\n").length;
    // alert(strCount);
    var height = 30+(strCount-2)*16;
    $(trg).css('height', (height > 30 ? height : 30) +'px');

    $(trg).appendChild('input');
}

function addCombination(event) {
    var trg = event.target || event.srcElement;

    var combDiv = $(trg).parent().children('div.content').children('div[name=combDiv]:hidden');
    var newCombDiv = combDiv.clone();
    
    newCombDiv.appendTo(combDiv.parent());
    newCombDiv.show();

}

function deleteComb(event) {
    var trg = event.target || event.srcElement;
    $(trg).parent().remove();
}

function pathChanged(event) {
    //var newVal = $("div#coDiv_"+coId+" > form > textarea[name=path]").val();
    //$("span#coSpan_"+coId).text(newVal);
    var trg = event.target || event.srcElement;
    //    $(trg).parent().parent().parent().find('span[id|=coSpan_]').text($(trg).val());
    $(trg).parent().parent().parent().find('div#rightnow h3.reallynow span').text($(trg).val());
}

function saveConfig() {
    //alert('hello');

    var cos = new Array();
    var coIndex = 0;

    //var labId = $('input#labId').val();
    var courseId = $('input#courseId').val();
    var labNumber = $('input#labNumber').val();


    $('div[name=coContainer]:visible > div[id!=rightnow] > form').each(function() {
        //var ser = $(this).serialize();
        //alert('ser = '+ser);

        var co = new Object();

        co.id = $(this).children('input[name=id]').val();
        co.path = $(this).children('textarea[name=path]').val();
        
        co.type = $(this).children('select[name=type]').val();
        if(co.type == undefined || co.type == null) {
            co.type = $(this).children('input[name=type]').val();
        }
        
        
        //        alert('id: '+co.id+'; path: '+co.path + '; type: '+co.type);

        /* WHY DOESN'T WORK ?!
        $(this).children('div.content > div[name=combDiv]:visible > textarea').each(function() {
            alert('hooray!');
        });
        */

        var combArray = new Array();
       
        var i = 0;

        $(this).children('div.content').each(function() {
            $(this).children('div[name=combDiv]:visible').each(function() {
                $(this).children('textarea').each(function() {
                    var comb = $(this).val();
                    combArray[i++] = comb;
                });
            });
        });

        if(combArray.length > 0) {
            co.combs = combArray;
        }

        cos[coIndex++] = co;
    });

    var cosJSON = JSON.stringify(cos);
    $.ajax({
        type: "POST",
        url: "UpdateConfig",
        data: ({
            json    : cosJSON
            ,
            courseId : courseId
            ,
            labNumber : labNumber
        //labId : labId
        }),
        success: function(msg){
            alert('Настройки сохранены');
                
            if(msg) {
                var idArr = eval('(' + msg + ')');

                for(var respIndex = 0; respIndex < idArr.length; respIndex++) {
                    //alert('replace '+idArr[respIndex].tempId+' -> '+idArr[respIndex].newId);
                    var tempId = idArr[respIndex].tempId;
                    var newId = idArr[respIndex].newId;
                    $('div.newContainer:visible').each(function() {
                        var divTempId = $(this).children('input[name=tempId]').val();
                        if(divTempId == tempId) {
                            // html = html.replace(new RegExp(tempId,'g'), newId);
                            //alert('replaced');
                            
                            $(this).children('input[name=tempId]').remove();
                            $('span#coSpan_'+tempId).attr('id', 'coSpan_'+newId);
                            $('div#coDiv_'+tempId).attr('id', 'coDiv_'+newId);

                            //$('div#coDiv_'+newId+' > form#form > textarea[name=path]').hide();

                            $('div#coDiv_'+newId+' > form#form > textarea[name=path]').attr('onchange', 'pathChanged('+newId+')');



                            $(this).removeClass('newContainer');
                        }
                    })
                }
            //var idArray = eval('('+msg+'+');
            //alert(idArray);
            }

        },
        error: function(err){
            alert('Ошибка сохранения настроек: '+err+'.\nПожалуйста, обратитесь к администратору.');
        }
    });

/*
    $('div[name=coContainer]').each(function() {
        alert('container')
       $(this).children('div:visible').each(function() {
            
       })
    });
*/
}

var tempId = -1;
function getTempId() {
    //return $('div[name=coContainer]:hidden > input:hidden').val();
    return tempId-- ;
}

function addObject() {
    var containerDiv = $('div#box > div > div[name=coContainer]:hidden');//.show();
    var newContainerDiv = containerDiv.clone();

    var html = newContainerDiv.html();
    html = html.replace(/'%TEMP_ID%'/g, getTempId())
    newContainerDiv.html(html);


    newContainerDiv.appendTo(containerDiv.parent());
    newContainerDiv.show();
}

function delObject(event) {
    if(confirm('Вы уверены, что хотите удалить объект проверки?')) {
        var trg = event.target || event.srcElement;
        $(trg).parent().parent().parent().remove();
    }
//$(trg).parent('div[name=coContainer]').remove();
}

function showDescription(courseId, labNumber) {
    var initVal = $('input#showDescBtn').val();
    $('input#showDescBtn').val('Запрос описания...')
    $.ajax({
        url: 'LabDescription?courseId='+courseId+'&labNumber='+labNumber,
        success: function(msg){
            $('input#hideDescBtn').show();
            $('input#showDescBtn').hide();
            $('input#showDescBtn').val(initVal);
            $('div#checkContainer').css('width', '75%');
            if(msg == null || msg.length < 1
                || (msg.length == 6 && msg.indexOf('null') != -1)
                || (msg.length == 2 && msg.indexOf('\n') != -1)
                ) {
                $('div#task').html('Описание не найдено');
            } else {
                $('div#task').html(msg);
            }
            $('div#task').show();
        }
    });
}

function hideDescription() {
    $('input#hideDescBtn').hide();
    $('input#showDescBtn').show();

    $('div#task').hide();
    $('div#checkContainer').css('width', '100%');
}



function ftpInspect(event, courseId, index, path, type) {
    var trg = event.target || event.srcElement;
    var initialVal = $(trg).val();
    $(trg).val('Проверяется...');

    $.ajax({
        url: "FtpInspect",
        type: "POST",
        data: {
            courseId: courseId,
            // labNumber: labNumber,
            path: path,
            type: type
        },
        success: function(data){
            $(trg).val(initialVal);
            try {
                $('div#objectContentDiv_'+index).hide();
            } catch (e) {}
            if(data != null && data.length > 0 && data != 'null') {
                $('textarea#objectContent_'+index).show();
                $('textarea#objectContent_'+index).text(data);

                $(trg).next().show();
                $(trg).next().next().show(); // highlight button
            } else {
                alert('Объект не найден, либо пуст');
            }
        }
        ,
        error: function() {
            $(trg).val(initialVal);
            try {
                $('div#objectContentDiv_'+index).hide();
            } catch (e) {}
            alert("Произошла ошибка.\nПожалуйста, обратитесь к администратору.");
        }
    });
}

function highlight(index) {

    var ta = $('textarea#objectContent_'+index);

    var combs = new Array();
    var i = 0;
    ta.parent().find('textarea[name=taComb]').each(function() {
        combs[i++] = $(this).text();
    })
    
    if(combs == null || combs.length < 1) {
        return;
    }
    
    var div = $('div#objectContentDiv_'+index);

    var text = ta.text();
    text = text.replace(/ /g, '&nbsp;');
    text = text.replace(/\n/g, '<br/>');

    //    div.html(text);
    //    text = div.text();
    
    for(var combIndex = 0; combIndex < combs.length; combIndex++) {
        //            str.replace(new RegExp("тест",'g'),"прошел")
        text = text.replace(new RegExp(combs[combIndex],"gi"),
            '<span style="text-weight: bold; background: lightgreen;">'+combs[combIndex]+'</span>');
    }
    div.html(text);
    ta.hide();
    div.show();
}

function hideContentTextarea(event, index) {
    var trg = event.target || event.srcElement;
    $(trg).hide();
    $(trg).next().hide(); //highlight button

    $('textarea#objectContent_'+index).hide();
    $('div#objectContentDiv_'+index).hide();
//    var trg = event.target || event.srcElement;
//    $(trg).next().next().hide(); // now is highlight button
//    $(trg).next().next().next().hide();
//    $(trg).hide();
}